package com.filldream.fastboot.core.job.quartz;

import com.filldream.fastboot.base.entity.QuartzJob;
import com.filldream.fastboot.base.entity.QuartzLog;
import com.filldream.fastboot.base.mapper.SysQuartzLogMapper;
import com.filldream.fastboot.common.util.SpringContextHolder;
import com.filldream.fastboot.core.cache.CacheUtil;
import com.filldream.fastboot.core.service.ScheduleJobService;
import com.filldream.fastboot.core.thread.ThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.util.concurrent.*;

@Slf4j
public class ExecutionJob extends QuartzJobBean {

    @Override
    public void executeInternal(JobExecutionContext context) {
        // 获取任务
        QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzJob.JOB_KEY);
        // 获取spring bean
        SysQuartzLogMapper quartzLogRepository = SpringContextHolder.getBean(SysQuartzLogMapper.class);
        ScheduleJobService quartzJobService = SpringContextHolder.getBean(ScheduleJobService.class);

        String uuid = quartzJob.getUuid();

        QuartzLog quartzLog = new QuartzLog();
        quartzLog.setJobId(quartzJob.getId());
        quartzLog.setJobName(quartzJob.getJobName());
        quartzLog.setBeanName(quartzJob.getBeanName());
        quartzLog.setMethodName(quartzJob.getMethodName());
        quartzLog.setParams(quartzJob.getParams());
        long startTime = System.currentTimeMillis();
        quartzLog.setCronExpression(quartzJob.getCronExpression());
        try {
            // 执行任务
            QuartzRunnable task = new QuartzRunnable(quartzJob.getBeanName(), quartzJob.getMethodName(), quartzJob.getParams());
            Future<?> future = ThreadPoolUtil.J.getExecutor().submit(task);
            future.get();
            long times = System.currentTimeMillis() - startTime;
            quartzLog.setTime(times);
            if(StringUtils.isNotBlank(uuid)) {
                CacheUtil.cacheObj(uuid,"1");
            }
            // 任务状态
            quartzLog.setIsSuccess(1);
            log.info("任务执行成功，任务名称：" + quartzJob.getJobName() + ", 执行时间：" + times + "毫秒");
            // 判断是否存在子任务
            if(StringUtils.isNotBlank(quartzJob.getSubTask())){
                String[] tasks = quartzJob.getSubTask().split("[,，]");
                // 执行子任务
                quartzJobService.executionSubJob(tasks);
            }
        } catch (Exception e) {
            System.out.println("任务执行失败:" + e.toString());
            if(StringUtils.isNotBlank(uuid)) {

            }
            log.error("任务执行失败，任务名称：" + quartzJob.getJobName());
            long times = System.currentTimeMillis() - startTime;
            quartzLog.setTime(times);
            quartzLog.setIsSuccess(0);
            quartzLog.setExceptionDetail( e.getMessage() );
            // 任务如果失败了则暂停
            if(quartzJob.getPauseAfterFailure() != null && quartzJob.getPauseAfterFailure() == 0){
                quartzJob.setIsPause(1);
                //更新状态
                quartzJobService.updateIsPause(quartzJob);
            }
            if(quartzJob.getEmail() != null){
//                EmailService emailService = SpringContextHolder.getBean(EmailService.class);
//                // 邮箱报警
//                if(StringUtils.isNoneBlank(quartzJob.getEmail())){
//                    EmailVo emailVo = taskAlarm(quartzJob, ThrowableUtil.getStackTrace(e));
//                    emailService.send(emailVo, emailService.find());
//                }
            }
        } finally {
            quartzLogRepository.insert(quartzLog);
        }
    }

}